package com.foogui.aop;

import com.foogui.mapper.SysLogMapper;
import com.foogui.service.SysLogService;
import com.foogui.util.IpUtil;
import com.foogui.util.RequestUtil;
import com.foogui.vo.SysLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Aspect
@Component
public class LogAop {
    @Resource
    private SysLogService sysLogService;

    @Resource
    private IpUtil ipUtil;

    @Resource
    private RequestUtil requestUtil;
    @Around("execution(* com.foogui.service..*.*(..))")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        //获取方法名
        String methodName=point.getSignature().getName();
        if ("login".equals(methodName)){
            try{
                //这里可以做一些前置处理
                //todo...
                result = point.proceed();
                //登录成功返回User即为result
                if (result!=null){
                    //保存登录日志
                    SysLog sysLog = new SysLog();
                    sysLog.setCreateTime(new Date());
                    sysLog.setMethod(methodName);
                    //实际开发应为((SysUser)result).getUserName()，这里假设admin
                    sysLog.setUsername("admin");
                    //获取ip地址
                    HttpServletRequest request = requestUtil.getRequest();
                    String ip = ipUtil.getIpAddr(request);
                    sysLog.setIp(ip);
                    sysLogService.save(sysLog);
                }
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        //放行
        return result;
    }


}
